package io.renren.membermanage.controller;

import cn.dev33.satoken.stp.SaLoginModel;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import io.renren.membermanage.dto.LoginParam;
import io.renren.membermanage.dto.RegisterParam;
import io.renren.membermanage.entity.SysUser;
import io.renren.membermanage.service.LoginService;
import io.renren.membermanage.service.SysUsersService;
import io.renren.util.ApiResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/member")
@Tag(name = "登入")
public class LoginController {

    @Resource
    private LoginService loginService;

    @Resource
    private SysUsersService sysUsersService;

    /**
     * 生成图片验证码
     * @param response
     * @param uuid
     * @throws Exception
     */
    @GetMapping("captcha")
    @Operation(summary = "生成图片验证码", description = "生成图片验证码")
    @ApiResponses(value ={
            @ApiResponse(responseCode = "200", description = "请求成功", content = @Content),
            @ApiResponse(responseCode = "400", description = "请求失败", content = @Content)
    })
    public void captcha(HttpServletResponse response, @RequestParam("uuid") String uuid) throws Exception{
        loginService.createCaptcha(response, uuid);
    }

    @PostMapping("register")
    @Operation(summary = "注册", description = "注册")
    @ApiResponses(value ={
            @ApiResponse(responseCode = "200", description = "请求成功",
                    content = @Content(mediaType = "application/json", schema = @Schema(implementation = Map.class))),
            @ApiResponse(responseCode = "400", description = "请求失败", content = @Content)
    })
    public ApiResult<Map<String, String>> register(@RequestBody RegisterParam param) {
        Map<String, String> map = new HashMap<>();
        Long id = sysUsersService.addMember(param);
        StpUtil.login(id, new SaLoginModel().setDevice(param.getEquipment()).setIsWriteHeader(false));
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        map.put(tokenInfo.getTokenName(), tokenInfo.getTokenValue());
        return ApiResult.success(map);
    }

    /**
     * 登入并返回页面token,同端互斥登入
     * @param param
     * @return
     */
    @PostMapping("login")
    @Operation(summary = "登入", description = "登入")
    @ApiResponses(value ={
            @ApiResponse(responseCode = "200", description = "请求成功",
                    content = @Content(mediaType = "application/json", schema = @Schema(implementation = Map.class))),
            @ApiResponse(responseCode = "400", description = "请求失败", content = @Content)
    })
    public ApiResult<Map<String, String>> login(@RequestBody LoginParam param) {
        loginService.checkCaptcha(param.getCaptchaKey(), param.getCaptchaValue());
        SysUser member = sysUsersService.verify(param.getMemberName(), param.getMemberPassword());
        if(null == member){
            return ApiResult.fail("用户名或密码错误");
        }
        // 第1步，先登录上
        StpUtil.login(member.getId(), new SaLoginModel().setDevice(param.getEquipment()).setIsWriteHeader(false));
        // 第2步，获取 Token  相关参数
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        // 第3步，返回给前端
        Map<String, String> map = new HashMap<>();
        map.put(tokenInfo.getTokenName(), tokenInfo.getTokenValue());
        map.put("userId", member.getId().toString());
        map.put("userName", member.getUsername());
        return ApiResult.success(map);
    }
}
